package base

import (
	"fmt"
	"io"
	"net"
	"os"
)

type Client struct {
	ServerIp   string
	ServerPort int
	Name       string
	conn       net.Conn
	flag       int
}

func NewClient(serverIp string, serverPort int) *Client {
	// 创建客户端对象
	client := &Client{
		ServerIp:   serverIp,
		ServerPort: serverPort,
		flag:       999,
	}
	// 连接服务器
	conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", serverIp, serverPort))
	if err != nil {
		return nil
	}
	client.conn = conn
	// 返回客户端对象
	return client
}

// 处理服务器端返回的消息
func (c *Client) DealResponse() {
	// 循环的读取服务器发送的消息
	io.Copy(os.Stdout, c.conn)
	defer c.conn.Close()
}

// 显示菜单
func (c *Client) menu() bool {
	fmt.Println("1.公聊模式")
	fmt.Println("2.私聊模式")
	fmt.Println("3.更新用户名")
	fmt.Println("0.退出")
	fmt.Print("请选择(0-3):\n")
	var flag int
	fmt.Scanf("%d\n", &flag)
	if flag >= 0 && flag <= 3 {
		c.flag = flag
		return true
	} else {
		return false
	}
}

// 查询用户
func (c *Client) SelectUsers() {
	msg := "who\n"
	c.conn.Write([]byte(msg))
}

// 私聊模式
func (c *Client) PrivateChat() {
	c.SelectUsers()
	fmt.Println(">>>请输入聊天对象(用户名),exit退出")
	var name string
	fmt.Scan(&name)
	if name == "exit" {
		return
	}
	fmt.Println(">>>请输入聊天内容,exit退出")
	var chatMsg string
	fmt.Scanf("%s\n", &chatMsg)
	for chatMsg != "exit" {
		if len(chatMsg) != 0 {
			c.conn.Write([]byte("to|" + name + "|" + chatMsg + "\n\n"))
		}
		chatMsg = ""
		fmt.Println(">>>请输入聊天内容,exit退出")
		fmt.Scanf("%s\n", &chatMsg)
	}
}

// 公聊模式
func (c *Client) PublicChat() {
	fmt.Println(">>>请输入聊天内容,exit退出")
	var chatMsg string
	fmt.Scanf("%s\n", &chatMsg)
	for chatMsg != "exit" {
		if len(chatMsg) != 0 {
			c.conn.Write([]byte(chatMsg + "\n"))
		}
		chatMsg = ""
		fmt.Println(">>>请输入聊天内容,exit退出")
		fmt.Scanf("%s\n", &chatMsg)
	}
}

// 更新用户名
func (c *Client) UpdateName() bool {
	fmt.Println(">>>请输入用户名:")
	fmt.Scanf("%s\n", &c.Name)
	c.conn.Write([]byte("rename|" + c.Name + "\n"))
	return true
}

func (c *Client) Run() {
	for c.flag != 0 {
		for !c.menu() {
		}
		// 根据不同的模式处理不同的业务'
		switch c.flag {
		case 1:
			fmt.Println("公聊模式")
			c.PublicChat()
		case 2:
			fmt.Println("私聊模式")
			c.PrivateChat()
		case 3:
			fmt.Println("更新用户名")
			c.UpdateName()
		}
	}
}
